package com.example.zsr.akpautoupdatedemo;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.zsr.akpautoupdatedemo.JsonUtils.Android_ireader;
import com.example.zsr.akpautoupdatedemo.JsonUtils.Root;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhengshaorui on 2016/12/18.
 */

public class CheckLocalInfo extends AsyncTask<String,Integer,String>{
    private static final String TAG = "zsr";

    private Context mContext;
    private int mVersionCode;

    public CheckLocalInfo(Context context){
        this.mContext = context;
        this.mVersionCode = getLocalInfo(mContext).versionCode;
    }
    @Override
    protected String doInBackground(String... strings) {
        String JsonString = GetJsonFromServer(mContext,strings[0]);
        return JsonString;
    }

    @Override
    protected void onPostExecute(String s) {
        handleJson(s);
        super.onPostExecute(s);
    }

    /**
     * 获取Androidmainfest.xml的versionCode
     * @param context
     * @return
     */
    public PackageInfo getLocalInfo(Context context) {
        PackageInfo mPackageInfo = null;
        try {
            mPackageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mPackageInfo;
    }

    /**
     * 解析json数据，然后检查是否更新，对比versionCode
     * @param json
     */
    private void handleJson(String json){
        Gson mGson = new Gson();
        java.lang.reflect.Type type = new TypeToken<Root>() {}.getType();
        Root root = mGson.fromJson(json, type); //

        Android_ireader apk = root.getAndroid_ireader();

        int newVersionCode = apk.getVersion_code();

        int compareVersionResult = newVersionCode - mVersionCode;

        if (compareVersionResult > 0) {
            //可以更新
            Intent dialogIntent = new Intent(mContext,UpdateDialogActivity.class);
            dialogIntent.putExtra("versionname",apk.getApp_version());
            dialogIntent.putExtra("content", apk.getFeatures());
            dialogIntent.putExtra("apkurl", apk.getUpdate_url());
            mContext.startActivity(dialogIntent);

        }else{
            Toast.makeText(mContext, "已是最新版本", Toast.LENGTH_SHORT).show();
        }


    }


    /**
     * 从服务器中获取Json数据并返回
     * @param context
     * @param url
     * @return
     */
    private String GetJsonFromServer(Context context,String url){
        StringBuffer sb = null;
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(3000);
            Log.d(TAG, "code: "+conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                sb = new StringBuffer();
                String string = null;
                while ((string = br.readLine()) != null) {
                    sb.append(string);
                }

            }else{
                Toast.makeText(context,"connect fail: "+conn.getResponseCode(),Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            conn.disconnect();
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (sb == null)
            return "null";
        return sb.toString();
    }


}
